//
//  QJNearVCShopDetailVC.m
//  QuanJieShopProject
//
//  Created by 刘中义 on 2018/2/14.
//  Copyright © 2018年 apple. All rights reserved.
//

#import <BaiduMapAPI_Location/BMKLocationComponent.h>//引入定位功能所有的头文件
#import <BaiduMapAPI_Utils/BMKUtilsComponent.h>
#import <BaiduMapAPI_Map/BMKMapComponent.h>
#import <BaiduMapAPI_Search/BMKSearchComponent.h>

#import "BaiduMapAPI_Utils/BMKNavigation.h"

#import "QJNearVCShopDetailVC.h"

#import "QJNearShopDetailHeaderView.h"
#import "YFMapNavigationViewController.h"
//定位
#import <MapKit/MapKit.h>
@interface QJNearVCShopDetailVC () <UITableViewDelegate,UITableViewDataSource,CLLocationManagerDelegate>
@property (nonatomic, strong) UITableView *shopDetailTableView;
@property (nonatomic, strong) QJNearShopDetailHeaderView *detailHeaderView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) NSDictionary *dataDic;
@property (strong,nonatomic) CLLocationManager *locationManager;
@end

@implementation QJNearVCShopDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"店铺详情";
   
    [self setupUIAction];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:YFColor_Red]
                                                  forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc]init]];
    
    [self dataRequestAction];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self setNavAlpha:NO];
}
#pragma mark -- 界面布局方法
- (void)setupUIAction{
    WEAKSELF
    self.detailHeaderView = [[[NSBundle mainBundle]loadNibNamed:@"QJNearShopDetailHeaderView" owner:self options:nil] lastObject];
    self.detailHeaderView.frame = CGRectMake(0, 0, UISCREEN_WIDTH, 550);
    
    self.shopDetailTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, UISCREEN_WIDTH, UISCREEN_HEIGHT) style:UITableViewStylePlain];
    [self.view addSubview:self.shopDetailTableView];
    self.shopDetailTableView.delegate = self;
    self.shopDetailTableView.dataSource = self;
    self.shopDetailTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.shopDetailTableView.tableHeaderView = self.detailHeaderView;
    self.detailHeaderView.headerBtnClickBlock = ^(NSInteger tag) {
        switch (tag) {
            case 200:
            {
                [weakSelf alertMapWithLocation];
            }
                break;
            case 201:
            {
                [weakSelf telephoneAction];
            }
                break;
            case 202:
            {
                [weakSelf alertMapWithLocation];
            }
                break;
            default:
                break;
        }
    };
    
}
#pragma mark -- 数据请求方法
- (void)dataRequestAction{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:self.shopID forKey:@"shopid"];
    NSLog(@"商铺详情 dict = %@", dict);

    [WWNetRequest fetchShopDetailWithParameters:dict success:^(id response) {
        NSLog(@"商铺详情 response = %@", response);
        if ([response isKindOfClass:[NSDictionary class]]) {
            WEAKSELF
            [weakSelf.detailHeaderView headerUpdateDataWithDic:response[@"data"]];
            weakSelf.dataDic = response[@"data"];
        }
    } failure:^(NSDictionary *error) {
        NSLog(@"商铺详情 error = %@", error);

    }];
}
#pragma mark -- UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"UITableViewCell" owner:self options:nil] lastObject];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
#pragma mark -- 地图导航功能

//打开导航(经纬度)
- (void)alertMapWithLocation{
    
    /*
    BMKPlanNode *startPoint = [[BMKPlanNode alloc] init];
    
    BMKPlanNode *endPoint = [[BMKPlanNode alloc] init];
    endPoint.pt = CLLocationCoordinate2DMake(30.06621, 112.221186);
    
    BMKNaviPara *para = [[BMKNaviPara alloc] init];
    para.startPoint = startPoint;
    para.endPoint = endPoint;
    
    [BMKNavigation openBaiduMapNavigation:para];
    
    YFMapNavigationViewController *vc = [[YFMapNavigationViewController alloc] init];
    KPushViewControllerAction(vc);
    */
    
    //*

    CGFloat logStr = [[YFSaveTool userDefaults:@"LOG"] floatValue];
    CGFloat latStr = [[YFSaveTool userDefaults:@"LAT"] floatValue];
    KMyLog(@"logStr = %f, latStr = %f", logStr, latStr);
    if (logStr && latStr) {
        
    }
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"导航" message:@"请选择您的导航地图" preferredStyle:UIAlertControllerStyleActionSheet];
    if ([self canOpenUrl:@"iosamap://"]) {
        UIAlertAction *GDAction = [UIAlertAction actionWithTitle:@"高德地图" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            // 百度转高德
            // 自己的位置
            CLLocationCoordinate2D myLocaion_Baidu = CLLocationCoordinate2DMake(latStr, logStr);
            CLLocationCoordinate2D myLocaion_GaoDe = [YFLocationConverter bd09ToGcj02:myLocaion_Baidu];

            // 商铺位置
            NSString *lat = self.dataDic[@"latitude"];
            NSString *log = self.dataDic[@"longitude"];
            CLLocationCoordinate2D shop_Baidu = CLLocationCoordinate2DMake([lat doubleValue], [log doubleValue]);
            CLLocationCoordinate2D shop_GaoDe = [YFLocationConverter bd09ToGcj02:shop_Baidu];
            
            NSString *urlString = [[NSString stringWithFormat:@"iosamap://path?sourceApplication=applicationName&sid=BGVIS1&slat=%f&slon=%f&sname=%@&did=BGVIS2&dlat=%f&dlon=%f&dname=%@&dev=0&m=0&t=0",myLocaion_GaoDe.latitude,myLocaion_GaoDe.longitude,@"我的位置",shop_GaoDe.latitude,shop_GaoDe.longitude,self.dataDic[@"shop_name"]]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            NSURL *r = [NSURL URLWithString:urlString];
            [[UIApplication sharedApplication] openURL:r];
        }];
        
        [alertVC addAction:GDAction];
    }else if ([self canOpenUrl:@"baidumap://"]) { // gcj02
        UIAlertAction *BDAction = [UIAlertAction actionWithTitle:@"百度地图" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSString *urlString = [[NSString stringWithFormat:@"baidumap://map/direction?origin={{我的位置}}&destination=latlng:%@,%@|name=%@&mode=driving&coord_type=BD09",self.dataDic[@"latitude"],self.dataDic[@"longitude"],self.dataDic[@"shop_name"]] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//            KMyLog(@"urlString = %@", urlString);
//            KMyLog(@"shop_name = %@", self.dataDic[@"shop_name"]);
            NSURL *url = [NSURL URLWithString:urlString];
            [[UIApplication sharedApplication] openURL:url];
        }];
        [alertVC addAction:BDAction];
        
    }else{
        UIAlertAction *systemAction = [UIAlertAction actionWithTitle:@"苹果地图" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //当前位置
            MKMapItem *currentLocation = [MKMapItem mapItemForCurrentLocation];
            currentLocation.name = @"我的位置";
            
            //目标位置
            CLLocationCoordinate2D baiduLoc = CLLocationCoordinate2DMake([self.dataDic[@"latitude"] doubleValue],[self.dataDic[@"longitude"] doubleValue]);
            // 百度坐标转苹果, 苹果地图用的高德地图数据
            CLLocationCoordinate2D loc = [YFLocationConverter bd09ToGcj02:baiduLoc];
            
            MKMapItem *toLocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:loc addressDictionary:nil]];
            toLocation.name = [NSString stringWithFormat:@"%@",self.dataDic[@"shop_name"]];
            //打开苹果自身地图
            [MKMapItem openMapsWithItems:@[currentLocation, toLocation]launchOptions:@{MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving, MKLaunchOptionsShowsTrafficKey: [NSNumber numberWithBool:YES]}];
        }];
        [alertVC addAction:systemAction];
    }
    UIAlertAction *CanleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }] ;
    
    [alertVC addAction:CanleAction];
    [self presentViewController:alertVC animated:YES completion:nil];
     
     //*/
}
#pragma mark -- 判断是否安装了某个地图
- (BOOL)canOpenUrl:(NSString *)string{
    return [[UIApplication sharedApplication]canOpenURL:[NSURL URLWithString:string]];
}
#pragma mark -- 打电话功能
- (void)telephoneAction{
    [YFGlobalTool callWithPhoneNumber:self.dataDic[@"tel"]];
}
#pragma mark -- 懒加载
- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
